//引入数据库
const db = require('../db/index')

//引入bcryptjs,对密码进行加密操作
const bcrypt = require('bcryptjs')

//导入自动生成token的包和密钥
const jwt = require('jsonwebtoken')
const jwtSecretKey = require('../config')

//注册新用户函数    参数：username、password、user_tel
exports.register = (req, res) => {
    //接收表单数据
    const userinfo = req.body
        //检验是否电话被注册
    const selectSql = "select * from user where user_tel=?"
    db.query(selectSql, userinfo.user_tel, (err, results) => {
        if (err) return res.cc(err)

        if (results.length > 0) {
            return res.cc("电话号码已经被注册，请重新输入!")
        }

        //调用bcrypt.hashSync()对密码进行加密
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)

        //将加密后的密码、用户名、电话号码保存到数据库中
        const insertSql = "insert into user set ?"
        db.query(insertSql, { username: userinfo.username, password: userinfo.password, user_tel: userinfo.user_tel }, (err, results) => {
            if (err) return res.cc(err)

            // 判断影响的行数是否为1
            if (results.affectedRows !== 1) return res.cc("注册用户失败，请稍后再试")

            res.send({
                status: 0,
                message: "注册成功!"
            })
        })
    })

}


//登录函数  参数：user_tel、password
exports.login = (req, res) => {
    const userinfo = req.body
        // console.log(userinfo);
    const selectSql = "select * from user where user_tel=?"
    db.query(selectSql, userinfo.user_tel, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc("登录失败!")

        //用于解密判断密码是否匹配
        const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
        if (!compareResult) res.cc("登录失败!")

        //服务器生成token的字符串
        //展开运算符，去除敏感信息，使用赋值方式
        const user = {...results[0], password: '' } // console.log(user);

        req.user = user
            // console.log(req.user);

        // 进行token字符串的生成
        const tokenStr = jwt.sign(user, jwtSecretKey.key, { expiresIn: jwtSecretKey.hour })

        res.send({
            status: 0,
            message: "登录成功!",
            token: 'Bearer ' + tokenStr
        })

    })
}